package com.sg.java.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Pipeline;

import java.util.Set;

public class JedisUtils {

    private static volatile JedisPool jedisPool;

    public static void InitJedisPool(String host, int port, int timeout, String password) {
        if (jedisPool == null) {
            synchronized (JedisUtils.class) {
                if (jedisPool == null) {
                    JedisPoolConfig config = new JedisPoolConfig();
                    config.setMaxTotal(25);//最大连接数
                    config.setMaxIdle(25);//空闲连接数
                    config.setMaxWaitMillis(2 * 1000);
                    config.setTestOnBorrow(true);
                    //创建一个jedis，连接redis服务器
                    jedisPool = new JedisPool(config, host, port, timeout, password);
                }
            }

        }
    }

    //得到jedis对象
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    //关闭jedis对象
    public static void closeJedis(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    //得到jedis对象
    public static Pipeline getJp() {
        Jedis jedis = jedisPool.getResource();
        Pipeline pipelined = jedis.pipelined();
        return pipelined;
    }

    //获取某个键的值
//    public String get(String key){
//        Jedis jedis = getJedis();
//        String value = jedis.get(key);
//        closeJedis(jedis);
//        return value;
//    }
    //拿到所有键的集合
    public Set<String> keys(String key) {
        Jedis jedis = getJedis();
        Set<String> keys = jedis.keys(key);
        closeJedis(jedis);
        return keys;

    }

    public static Jedis newJedis() {
        final Jedis jedis = new Jedis("25.64.41.53", 6379, 100000);
        jedis.auth("Huawei@169");
        jedis.select(0);
        return jedis;
    }

}
